package cake.web.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import cake.dao.impl.CakeImgDaoImpl;
import cake.entity.CakeImg;
import util.FileUpLoad;

@WebServlet("/admin/cakeimgupdate.html")
public class AdminCakeImgUpdateServlet extends HttpServlet {

	private CakeImgDaoImpl cakeImgDaoImpl = new CakeImgDaoImpl();

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		long imageFile =0;
        int cid=0;
        
		FileUpLoad fileUpLoad = new FileUpLoad(request);
		System.out.println(fileUpLoad.getValue("cakeid"));
		cid=Integer.parseInt(fileUpLoad.getValue("cakeid"));
		
		List arr = fileUpLoad.getValues("deleteid");
		if (arr!=null) {
			for (int i = 0; i < arr.size(); i++) {
				int id = Integer.parseInt((String)arr.get(i));
				cakeImgDaoImpl.deleteImgById(id);
			}
		}

		List<FileItem> fileItems = fileUpLoad.getFileItemList("cakeimg");
		if (fileItems == null) {
			return;
		}
		for (int i = 0; i < fileItems.size(); i++) {
			if (!fileItems.get(i).getName().isEmpty()) {
				imageFile = System.currentTimeMillis()+1;
				String url = "/image/productImg/" + imageFile;
				String path = request.getServletContext().getRealPath(url);
				try {
					fileItems.get(i).write(new File(path));
				} catch (Exception e) {
					throw new RuntimeException("输出文件错误!!");
				}
				CakeImg cakeImg = new CakeImg(0, cid, imageFile+"");
				cakeImgDaoImpl.addImg(cakeImg);
			}
		}
		response.sendRedirect("cakelist.html");
	}
}
